package com.org.cloud.lg.custom;

import com.org.cloud.lg.api.MenuService;
import com.org.cloud.lg.api.UserService;
import com.org.cloud.lg.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * @ClassName: MyUserDetailsService
 * @Author: LG
 * @Date: 2019/3/7 11:54
 * @Version: 1.0
 **/
@Component("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    UserService userService;

    @Autowired
    MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        UserDto userDto= userService.findUserByUsername(userName);
        if (userDto == null) {
            throw new UsernameNotFoundException("账号或密码不正确");
        }
        // 账号锁定
        if (userDto.getStatus() == 1) {
            throw new UsernameNotFoundException("账号已被锁定,请联系管理员");
        }
        String userId=userDto.getId();
        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        Set<String> perms= menuService.selectPermsByUid(userId);
        for (String perm :perms) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(perm);
            grantedAuthorities.add(grantedAuthority);
        }
        CustomJwtUser customJwtUser=new CustomJwtUser(userDto.getUsername(),userDto.getPassword(),grantedAuthorities);
        customJwtUser.setUserId(userDto.getId());
        return customJwtUser;
    }
}
